<template>
    <form class="validate-form-container">
        <slot name="default"></slot>
        <div class="submit-area" @click.prevent="submitForm">
            <slot name="submit">
                <button class="btn btn-primary">提交</button>
            </slot>
        </div>
    </form>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue'
import mitt from 'mitt'
type validateFunc = () => boolean
type clearFunc = () => void
interface callbackProps {
    validator: validateFunc,
    clearInput: clearFunc
}
type Events = {
    'form-item-created': callbackProps
}
// 实例化mitt
export const emitter = mitt<Events>()
export default defineComponent({
    name: 'ValidateForm',
    emits: ['form-submit'],
    setup(props, context) {
        let funcArr: validateFunc[] = []
        let clearArr: clearFunc[] = []
        const submitForm = () => {
            const result = funcArr.map(func => func()).every(result => result)
            context.emit('form-submit', result)
            // 点击提交按钮后调用清除函数
            clearInputs()
        }
        const callback = (obj: callbackProps) => {
            funcArr.push(obj.validator)
            clearArr.push(obj.clearInput)
        }
        // 清空input值(点击提交按钮清空全部输入框)
        const clearInputs = () => {
            clearArr.forEach(clear => clear())
        }
        // 添加事件
        emitter.on('form-item-created', callback)
        onUnmounted(() => {
            // 删除事件监听
            emitter.off('form-item-created', callback)
            funcArr = []
            clearArr = []
        })
        return {
            submitForm,
            clearInputs
        }
    }
})
</script>
